package com.lhy.tool.patchplugin;

import com.lhy.tool.patchplugin.strategy.FileContext;
import com.lhy.tool.patchplugin.strategy.FileStrategy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 插件启动帮助类
 */
@Component
@Slf4j
public class PatchPluginHelper {

    @Autowired
    FileContext fileContext;

    @Autowired
    PatchPluginProperties patchPluginProperties;

    public void executes() {
        fileContext.executes(getPatchFiles());
    }

    public void setFileStrategies(List<FileStrategy> fileStrategies){
        fileContext.setFileStrategies(fileStrategies);
    }

    public PatchPluginHelper addFileStrategy(FileStrategy fileStrategies){
        fileContext.getFileStrategies().add(fileStrategies);
        return this;
    }

    @SneakyThrows
    private Set<File> getPatchFiles() {
        log.info("开始解析补丁文件：{}", patchPluginProperties.getPatchFilePath());
        List<String> readLines = FileUtils.readLines(new File(patchPluginProperties.getPatchFilePath()), "utf-8");
        Set<File> collect = readLines.stream()
                .map(line -> line.replace(patchPluginProperties.getSvnPath(),"Index: "))
                .filter(line -> line.startsWith("Index:") && !line.endsWith("pom.xml"))
                .sorted(String::compareTo)
                .map(line -> {
                    String temp = line.replaceAll(" ", "");
                    return temp.substring(temp.indexOf(":") + 1, temp.length());
                })
                .map(line -> {
                    File file = new File(line);
                    if (file.isAbsolute()) {
                        return file;
                    } else {
                        return new File(patchPluginProperties.getSrcPath() + "/" + line);
                    }
                })
                .collect(Collectors.toSet());
        //处理文件夹下的文件,加入到文件列表中 只会查找一级子文件夹，不会递归多级子文件夹
        Set<File> newFileList = new TreeSet<>(collect);
        collect.stream().filter(File::isDirectory)
                .forEach(file -> {
                    File[] files = file.listFiles(File::isFile);
                    if (files != null) {
                        Collections.addAll(newFileList, files);
                    }
                });
        log.info("文件数量：{}", newFileList.size());
        newFileList.forEach(file -> log.trace("patch文件行：" + file.getAbsolutePath()));
        return newFileList;
    }

}
